package com.atguigu.c_designed.m2stucturalModel.s7proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyClient {
    public static void main(String[] args) {
        CglibProxy cglibProxy = new CglibProxy(new TeacherDaoCglib());
        TeacherDaoCglib instance = (TeacherDaoCglib) cglibProxy.getInstance();
        String tom = instance.Teach2("tom ");
        System.out.println(tom);
    }
}

class TeacherDaoCglib {

    public String Teach2(String name) {
        System.out.println(name+"teacher teaching.....");
        return "I am  teacher " +name;
    }
}

class CglibProxy implements MethodInterceptor {

    private Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }

   public Object  getInstance(){
       Enhancer enhancer = new Enhancer();
       enhancer.setSuperclass(target.getClass());
       enhancer.setCallback(this);
       return enhancer.create();
   }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("proxy start....");
        Object invoke = method.invoke(target, args);
        System.out.println("proxy end....");
        return invoke;
    }
}
